import MdEditer from '@/components/MdEditer';
import Layout from '@/Layout';
import { ArticleType, OriginalType } from '@/services/creationCenter/typing.d';
import { ExclamationCircleFilled, SaveTwoTone } from '@ant-design/icons';
import { Button, Input, Modal, message } from 'antd';
import { ChangeEvent, useEffect, useState } from 'react';
import PublishForm from './components/PublishForm';
import styles from './index.scss';
import type { FormInfo } from './typing';
// 计算 markdown 字数
import { useMarkdownWordCount } from '@/hooks/useMarkdownWordCount';
import {
  getArticle,
  saveArticle,
  updatedArticle,
} from '@/services/creationCenter';
import { SaveArticleInfo } from '@/services/creationCenter/typing.d';
import { useParams } from '@umijs/max';

const { confirm } = Modal;

const Create: React.FC = () => {
  async function getArticleInfo(id: number) {
    const res = await getArticle(id);
    const {
      comment_num,
      create_time,
      page_view,
      popular,
      top_up,
      update_time,
      user_id,
      username,
      article_id,
      thumbs_up,
      ...articleDetail
    } = res.data;
    setArticleInfo((prev) => ({
      ...prev,
      ...articleDetail,
    }));
  }

  const { id } = useParams<string>();
  useEffect(() => {
    if (id) {
      // 编辑
      getArticleInfo(+id);
    }
  }, []);

  const [saveLoading, setSaveLoading] = useState<boolean>(false);
  const [articleInfo, setArticleInfo] = useState<SaveArticleInfo>({
    title: '未命名草稿',
    synopsis: '',
    tags: [],
    cover_img_url: '',
    type: ArticleType.DRAFT,
    content: '',
    words_num: 0,
    original: OriginalType.ISORIGINAL,
  });
  const { wordCount, text, onChange } = useMarkdownWordCount();
  const changeTitle = (e: ChangeEvent<HTMLInputElement>) => {
    setArticleInfo((prev) => ({
      ...prev,
      title: e.target.value,
    }));
  };

  const isRemindSave = (
    updatedArticleInfo: SaveArticleInfo,
    isDraft: Boolean,
  ): void => {
    const newArticleInfo = isDraft
      ? {
          type: ArticleType.DRAFT,
          title: updatedArticleInfo.title,
          content: text,
          words_num: wordCount,
          original: OriginalType.ISORIGINAL,
        }
      : {
          ...updatedArticleInfo,
          content: text,
          words_num: wordCount,
        };
    if (!text || !newArticleInfo.title) {
      confirm({
        title: '提醒',
        icon: <ExclamationCircleFilled />,
        content: '标题或者内容是空的，确定保存吗？',
        onOk() {
          if (!newArticleInfo.title) newArticleInfo.title = '未命名草稿';
          saveArticleInfo(newArticleInfo);
        },
      });
      return;
    }
    saveArticleInfo(newArticleInfo);
  };

  const saveArticleInfo = async (newArticleInfo: SaveArticleInfo) => {
    setSaveLoading(true);
    if (!id) {
      const res = await saveArticle(newArticleInfo);
      message.success(res.msg);
    } else {
      const res = await updatedArticle(+id, newArticleInfo);
      message.success(res.msg);
    }
    setSaveLoading(false);
  };

  // 获取抽屉中的值
  function confirmPublish(info: FormInfo) {
    const { coverImgList, ...otherInfo } = info;
    let cover_img_url = process.env.RANDOM_COVER_IMG;
    if (coverImgList && coverImgList.length > 0) {
      cover_img_url = coverImgList[0].url as string;
    }
    setArticleInfo((prev) => {
      const updatedArticleInfo = {
        ...prev,
        ...otherInfo,
        cover_img_url,
      };
      isRemindSave(updatedArticleInfo, false);
      return updatedArticleInfo;
    });
  }

  return (
    <Layout>
      <div className={styles.header}>
        <Input
          placeholder="未命名"
          size="large"
          allowClear
          value={articleInfo.title}
          className={styles.input}
          onChange={changeTitle}
        />
        <div className={styles.but_box}>
          <Button
            color="primary"
            variant="outlined"
            className={styles.btn_left}
            onClick={() => isRemindSave(articleInfo, true)}
            loading={saveLoading}
            icon={<SaveTwoTone />}
          >
            保存草稿
          </Button>
          <PublishForm
            initializeInfo={articleInfo}
            confirmPublish={confirmPublish}
          />
        </div>
      </div>

      <MdEditer defaultValue={articleInfo.content} onChange={onChange} />
    </Layout>
  );
};

export default Create;
